import model.ListNode;

public class Solution {
    //重排链表
    public void reorderList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null){
            return;
        }

        //寻找中间节点
        ListNode slow = head, fast = head;
        while (fast!= null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        //头插出新的一组
        ListNode newHead = new ListNode(0);
        ListNode cur = slow.next;
        slow.next = null;   //分离两个链表
        while (cur != null){
            ListNode next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;

            cur = next;
        }

        //合并两个链表
        ListNode cur1 = head, cur2 = newHead.next;
        ListNode ret = new ListNode(0);
        ListNode prev = ret;

        while (cur1 != null){
            prev.next = cur1;
            prev = cur1;
            cur1 = cur1.next;

            //合并第二个
            if (cur2 != null){
                prev.next = cur2;
                prev = cur2;
                cur2 = cur2.next;
            }
        }
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        //计算一共有多少组
        int count = 0;
        ListNode cur = head;
        while (cur != null){
            count++;
            cur = cur.next;
        }
        int n = count / k;

        ListNode newHead = new ListNode(0);
        ListNode prev = newHead;
        cur = head;

        for (int i = 0; i < n; i++){
            ListNode tmp = cur;
            //进行其中一组的头插排序
            for (int j = 0; j < k; j++){
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }

            prev = tmp;
        }

        prev.next = cur;
        return newHead.next;
    }

    }
    public static void main(String[] args) {
        Solution test = new Solution();
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        test.reorderList(node1);
    }
}
